﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Windows.Forms;
using ScreenUp.Properties;

namespace ScreenUp
{
    class ScreenUpFTPUploader
    {
        public void Upload(Bitmap screenUpBitmap, string userName, string password, int port, string hostname, string path, string HttpPrefix)
        {
            try
            {
                bool upload = false;
                if (Form1.df.PreviewBeforeUpload == true)
                {
                    if (new Preview(screenUpBitmap).ShowDialog() == DialogResult.Yes)
                    {
                        upload = true;
                    }
                }
                else
                {
                    upload = true;
                }
                if (upload == true)
                {
                    Program.f1.notifyIcon1.Icon = Resources.Network_Map;
                    string FileName2 = "ScreenGrab-" + new Random().Next(10000000, 99999999).ToString() + ".png";
                    string FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), FileName2);
                    screenUpBitmap.Save(FileName, ImageFormat.Png);

                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + hostname + path + "/" + FileName2);
                    request.Method = WebRequestMethods.Ftp.UploadFile;

                    // This example assumes the FTP site uses anonymous logon.
                    request.Credentials = new NetworkCredential(userName, password);

                    // Copy the contents of the file to the request stream.          
                    byte[] fileContents = File.ReadAllBytes(FileName);
                    request.ContentLength = fileContents.Length;

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(fileContents, 0, fileContents.Length);
                    requestStream.Close();

                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                    Program.f1.notifyIcon1.ShowBalloonTip(5, "ScreenGrab", String.Format("Upload File Complete, status {0}", response.StatusDescription), ToolTipIcon.Info);

                    response.Close();

                    Clipboard.SetText(HttpPrefix + "/" + FileName2);
                    Form1.df.ScreenGrabs.Add(HttpPrefix + "/" + FileName2 + "[" + DateTime.Now.ToString() + "]");
                    Program.SerializeDataFile(Form1.df);
                    File.Delete(FileName);
                }
            }
            catch (Exception ex) { Program.f1.notifyIcon1.ShowBalloonTip(5, "ScreenGrab", ex.Message, ToolTipIcon.Error); }
            Program.f1.notifyIcon1.Icon = Resources.Camera1;

        }
    }
}
